#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :zi_continued_provision_page.py
# Time  :2025/5/12 9:44
# Email :fortunatedong@163.com
# customer_name:by Adonli
import subprocess
import webbrowser

import pandas as pd
import streamlit as st
from xlsx2html import xlsx2html
from streamlit.components.v1 import html
from config import Header_space
import os
from config import ROOT_DIR
provision_excel_file_dir_path = os.path.join(ROOT_DIR, 'Datas/business_continued_provision/zi_provision_file_temp',)
success_mail_provision_dir_path = os.path.join(ROOT_DIR, 'Datas/business_continued_provision/zi_success_email_provision_file',)

Header_space()
st.subheader("机器（续）报备——邮件已发送表格申请记录", divider=True)
if "success_mail_provision_file_names_table_search_button" not in st.session_state:
    st.session_state.success_mail_provision_file_names_table_search_button = False
def success_mail_provision_file(success_mail_provision_dir_path):
    success_mail_provision_file_names = [
        entry.name for entry in os.scandir(success_mail_provision_dir_path)
        if entry.is_file()
    ]
    success_mail_provision_file_names_json = []
    for success_mail_provision_file_name  in success_mail_provision_file_names:
        file_name = success_mail_provision_file_name.split('.')[0]
        date = file_name.split('+')[0]
        brand = file_name.split('+')[1]
        customer_name = file_name.split('+')[2]
        success_mail_provision_file_names_json.append({"DATE": date, "Brand": brand, "customer_name": customer_name})
    # success_mail_provision_file_names_table = pd.DataFrame(success_mail_provision_file_names_json)
    return success_mail_provision_file_names_json


def search(success_mail_provision_file_names_table, email_send_start_date=None, email_send_end_date=None, customer_name=None):
    # 处理空字符串参数，将其视为None
    email_send_start_date = email_send_start_date if email_send_start_date else None
    email_send_end_date = email_send_end_date if email_send_end_date else None
    customer_name = customer_name if customer_name else None

    filtered_file_names_table = success_mail_provision_file_names_table.copy()

    # 转换日期格式为YYYY-MM
    if email_send_start_date is not None:
        email_send_start_date = email_send_start_date.strftime("%Y-%m-%d")  # 将datetime.date转换为YYYY-MM格式字符串
    if email_send_end_date is not None:
        email_send_end_date = email_send_end_date.strftime("%Y-%m-%d")  # 将datetime.date转换为YYYY-MM格式字符串

    # 筛选日期范围
    if email_send_start_date is not None or email_send_end_date is not None:

        filtered_file_names_table = [report for report in filtered_file_names_table
                          if (email_send_start_date is None or report["DATE"] >= email_send_start_date) and
                             (email_send_end_date is None or report["DATE"] <= email_send_end_date)]
        # 检查是否有匹配的日期范围
        if not filtered_file_names_table and (email_send_start_date is not None or email_send_end_date is not None):

            return {"code":404,"message":f"没有找到在{email_send_start_date if email_send_start_date else ''}到{email_send_end_date if email_send_end_date else ''}范围内的已发送邮件的报备申请表格"}



    # 筛选客户名称
    if customer_name is not None:
        customer_name_exists = any(customer_name == report["customer_name"] for report in filtered_file_names_table)
        if not customer_name_exists:
            return {"code": 404,"message": f"已发送邮件中，报备客户名称不存在: {customer_name}"}
        filtered_file_names_table = [report for report in filtered_file_names_table if customer_name == report["customer_name"]]

    return {"code": 200, "message": filtered_file_names_table}


success_mail_provision_file_names_json = success_mail_provision_file(success_mail_provision_dir_path)
# st.write(success_mail_provision_file_names_table)
col1, col2, col3, col4 = st.columns(4)
with col1:
    email_send_start_date = st.date_input(":blossom:**起始日期**", format="YYYY-MM-DD",value=None)
with col2:
    email_send_end_date = st.date_input(":blossom:**截止日期**", format="YYYY-MM-DD",value=None)
    if email_send_start_date is not None and email_send_end_date is not None:
        if email_send_end_date < email_send_start_date:
            st.warning("截止日期不能小于起始日期")
with col3:
    customer_name_option = [i["customer_name"] for i in success_mail_provision_file_names_json]
    customer_name = st.selectbox(":blossom:**报备客户名称**", customer_name_option, index=None, placeholder="选择报备客户名称")

with col4:
    col4_col1, col4_col2, col4_col3= st.columns(3)
    with col4_col2:
        st.write("")
        report_table_search_button = st.button("**搜索**")
        if report_table_search_button:
            st.session_state.success_mail_provision_file_names_table_search_button = True
            success_mail_provision_file_names_table_result = search(success_mail_provision_file_names_json, email_send_start_date, email_send_end_date, customer_name)
st.divider()
colms = st.columns((1, 1, 2, 1, 1))
fields = ["日期", '分支机构', '客户名称',"查看",'下载']
for col, field_name in zip(colms, fields):
    # header
    col.write(f"**{field_name}**")

if st.session_state.success_mail_provision_file_names_table_search_button:
    if success_mail_provision_file_names_table_result["code"] == 200:
        success_mail_provision_file_names_json = success_mail_provision_file_names_table_result["message"]
        st.session_state.success_mail_provision_file_names_table_search_button = False
    else:
        st.error(success_mail_provision_file_names_table_result["message"])
        st.session_state.success_mail_provision_file_names_table_search_button = False
        st.stop()

success_mail_provision_file_names_json = sorted(
    success_mail_provision_file_names_json,
    key=lambda x: x["DATE"],
    reverse=True
)

for i, row in enumerate(success_mail_provision_file_names_json):
    table_col1, table_col2, table_col3, table_col4, table_col5 = st.columns((1, 1, 2, 1, 1))
    DATE = row["DATE"]
    Brand = row["Brand"]
    customer_name = row["customer_name"]
    table_col1.write(DATE)
    table_col2.write(Brand)
    table_col3.write(customer_name)
    table_view_button = table_col4.button("查看表格",key=f"view{DATE}{Brand}{customer_name}")
    excel_filename = f"{DATE}+{Brand}+{customer_name}.xlsx"
    excel_path = os.path.join(success_mail_provision_dir_path, excel_filename)
    with open(f"{excel_path}", "rb") as f:
        table_col5.download_button(
            label="下载表格",
            data=f,
            file_name=f"{DATE}+{Brand}+{customer_name}.xlsx",
            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
    # 构建Excel文件路径

    if table_view_button:
        if os.path.exists(excel_path):
            # 方法1：使用xlsx2html原样显示（推荐）
            try:
                # 生成临时HTML文件
                html_path = f"temp/provision_html/zi_temp_报备申请表.html"
                xlsx2html(excel_path, html_path)

                # 读取HTML内容
                with open(html_path, "r", encoding="utf-8") as f:
                    html_content = f.read()

                # 用浏览器打开
                # webbrowser.open_new_tab(f"file://{os.path.abspath(html_path)}")
                js = f"""
                    <script>
                        window.open('http://1xx.xx.xx.xx:8000/{html_path}', '_blank');
                    </script>
                    """
                st.components.v1.html(js, height=0)
            except Exception as e:
                st.error(f"显示Excel时出错: {e}")
                # 备用方案：用pandas显示数据
                df = pd.read_excel(excel_path)
                st.dataframe(df)
        else:
            st.error("找不到指定的Excel文件")
